define(function() {
    var ec = require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');

    var zrUtil = require('zrender/tool/util');
    var zrnumber = require('echarts/util/number');
   
    var option = {
        backgroundColor: '#222',
        color: [
            '#ff4700',
            '#bd3a08',
            '#ff4700'
        ],
        grid: {
            x: '5%',
            y: '25%',
            x2: '2%',
            y2:'9%',
            borderWidth:0
        },
        title: {
            text: '',
            x:'left',
            y:'top',
            textStyle:{
                fontSize:28,
                color:'#858585'
            }
        },
        xAxis: [{
            type: 'category',
            splitLine:{
                show:false
            },
            axisLine:{
                show:false
            },
            axisTick:{
                show:false
            },
            axisLabel: {
            textStyle:{
                    color:'#858585'
                },
                interval: 59,
                formatter:function(value){
                    return value/60+'点';
                }
            },
            boundaryGap:false,
            data: function() {
                var x = [];
                for (var i = 0; i < 24*60; i++) {
                    x[i] = i;
                }
                return x;
            }()
        }],
        yAxis: [{
            type: 'value',
            show:true,
             axisLine:{
                show:false
            },
            splitLine:{
                lineStyle:{
                    color:['#2b2b2d']
                }
            },
            axisLabel: {
                textStyle:{
                    color:'#858585'
                },
                formatter:function(value){
                    return value/10000+'';
                }
            },
        }],
        series: [{
            name: 'dayline',
            type: 'line',
            smooth:true,
            symbol:'none',
            itemStyle:{
                normal:{
                    lineStyle:{
                        color:'#ff6921',
                        width:0.5
                    },
                    areaStyle: {
                        color:'rgba(229,94,31,.08) ',
                        type: 'default'
                    }
                }
            },
            data: [],
            markPoint: {
                data: [{
                    symbolSize:25,
                    itemStyle:{
                        normal:{
                            color:''
                        }
                    }
                }]
            }
        }]
    };

    
    function NetFlowChart(div_id){
        this.lasttime=null;
        this.option = zrUtil.clone(option);
        var title=$('#'+div_id).attr('name');
        if(title){
            this.option.title.text=title;
        };
        var lineColor=$('#'+div_id).attr('lineColor');
        if(lineColor){
            this.option.series[0].itemStyle.normal.lineStyle.color=lineColor;
            this.option.series[0].markPoint.data[0].itemStyle.normal.color=lineColor;
        };
        var areaColor=$('#'+div_id).attr('areaColor');
        if(areaColor){
            this.option.series[0].itemStyle.normal.areaStyle.color=areaColor;
        };
        this.myChart = ec.init(document.getElementById(div_id));
    }

    NetFlowChart.prototype.run = function(postUrl,postData){
        this.myChart.showLoading({
            text: '正在努力的读取数据中...'
        });
        //同步刷所有数据
        this.flushAll(false,postUrl,postData);
        //每2秒刷界面
        var self=this;
        clearInterval(timeTicket);
        var timeTicket = setInterval(function() {
            self.flushSec(true,postUrl,postData);
                }, 2 * 1000);
        //echart自适应
        $(window).resize(function(){
             self.myChart.resize();
        });
    };

    NetFlowChart.prototype.flushAll=function(async,postUrl,postData,notMerge){
        var self=this;
        $.ajax({
            url: postUrl,
            type: 'POST',
            async: async,
            data:postData,
            dataType: 'json',
            success:function(data){
                if (data.data && data.data.length > 0) {
                   self.lasttime = data.data[data.data.length - 1].time;
                   self.option.series[0].data=getSeriesData(data.data);
                   self.option.series[0].markPoint.data[0].xAxis=getXInedx(self.lasttime); 
                   var y = self.option.series[0].data;
                   self.option.series[0].markPoint.data[0].yAxis=y[y.length - 1]; 
                   self.option.series[0].markPoint.data[0].value=y[y.length - 1]; 
                };
                if(notMerge){
                	self.option.series[0].data=[];
                }
               self.myChart.setOption(self.option,notMerge);
               self.myChart.hideLoading();
            },
            timeout: 5000,
            error: function() {
               self.myChart.hideLoading();
            }
        });
    }

        NetFlowChart.prototype.flushSec=function(async,postUrl,postData){
        if (!this.lasttime) return;
                var self=this;
        $.ajax({
            url: '/dashboard/realtime/netflow/getHourData',
            type: 'POST',
            async: async,
            data: {
                            "type": postData.type,
                            "time": self.lasttime
                        },
            dataType: 'json',
            success:function(data){
                        if (!data.data || data.data.length == 0) return;
                        $.each(data.data,function(index,value){
                             var isChange=isChangeDay(self.lasttime,value.time);
                            self.lasttime=value.time;
                            var date=new Date(value.time);
                            if(date.getSeconds()==0){
                                self.flushAll(false,postUrl,postData,isChange);
                            }else{
                            var index=getXInedx(value.time);
                            var y = self.option.series[0].data;
                            if(y[index]){
                                y[index] = y[index] + value.value;
                            }else{
                                y[index]=value.value; 
                            }
                            self.option.series[0].markPoint.data[0].xAxis=index; 
                            self.option.series[0].markPoint.data[0].yAxis=y[index]; 
                            self.option.series[0].markPoint.data[0].value=y[index]; 
                             self.myChart.setOption(self.option);
                            }
                        });           
            },
            timeout: 1000,
            error: function() {
            }
        });
    }

    function getXInedx(time){
        var date=new Date(time);
        return date.getHours()*60+date.getMinutes();
        // return (time/(60*1000))%(24*60);
    }

        function getSeriesData(data){
            if(!data||data.length==0){
                return [];
            }
            var result=[];
            $.each(data,function(index,value){
                result.push(value.value);
            });
            return result;
        } 

        function isChangeDay(time1,time2){
            if(!time1){
                return false;
            }
            var day1=new Date(time1);
            var day2=new Date(time2);
            return day1.getDay()!=day2.getDay();
        }

        function toDouble(num){
            return parseInt(num,10) >= 10 ? '' + num : '0' + num;
        }

    function start() {

        clearInterval(timeTicket);
        var timeTicket = setInterval(function() {
            flushCash()
        }, 2 * 1000);
        /**
         *
         */
        function flushCash() {
            $.ajax({
                url: '/dashboard/realtime/netflow/getPvVppv',
                type: 'POST',
                async: true,
                dataType: 'json',
                success: function(data) {
                    var date=new Date(data.time);
                    var curDate = date.getFullYear() + '年' + toDouble((date.getMonth() + 1)) + '月' + toDouble(date.getDate()) + '日';
                    var curTime = toDouble(date.getHours()) + ':' + toDouble(date.getMinutes()) + ':' + toDouble(date.getSeconds());
                    var clickPv = data.click_pv;

                    $('.time').text(curTime);
                    $('.day').text(curDate);
                },
                timeout: 5000
            });
        }

        var pv=new NetFlowChart('pv');
        pv.run('/dashboard/realtime/netflow/getNetFlowByMin',{'type':'pv'});

        var vppv=new NetFlowChart('vppv');
        vppv.run('/dashboard/realtime/netflow/getNetFlowByMin',{'type':'vppv'});

    }

    return {
        'start': start
    };
});